package com.flyme.common.rpc.spring;

import com.flyme.common.rpc.spring.handler.AbstractInvocationHandler;
import com.flyme.common.rpc.spring.handler.DefaultInvocationHandler;
import com.flyme.common.rpc.spring.handler.EmptyInvocationHandler;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.Proxy;

/**
 * @param <T>
 * @author liyanxin
 */
public class ExportServiceProxyFactoryBean<T> implements FactoryBean<T> {

    private boolean definition;

    private Class<T> exportServiceInterface;

    public ExportServiceProxyFactoryBean() {
    }

    public ExportServiceProxyFactoryBean(Class<T> exportServiceInterface) {
        this.exportServiceInterface = exportServiceInterface;
    }

    @Override
    public T getObject() throws Exception {
        AbstractInvocationHandler invocationHandler;
        if (definition) {
            invocationHandler = new DefaultInvocationHandler();
        } else {
            invocationHandler = new EmptyInvocationHandler();
        }
        return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{this.exportServiceInterface}, invocationHandler);
    }

    @Override
    public Class<?> getObjectType() {
        return this.exportServiceInterface;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }


    public Class<T> getExportServiceInterface() {
        return exportServiceInterface;
    }

    public void setExportServiceInterface(Class<T> exportServiceInterface) {
        this.exportServiceInterface = exportServiceInterface;
    }

    public void setDefinition(boolean definition) {
        this.definition = definition;
    }
}
